//
//  QAWallAddQuestionViewController.m
//  HotWord
//
//  Created by liu huan on 13-3-19.
//
//

#import "QAWallAddQuestionViewController.h"
#import "QuestTagCategoryViewController.h"
#import "ServiceHelper.h"
#import "UserManager.h"
#import "QAWallViewController.h"

#define MAX_KEYBOARD_HEIGHT  252


@interface QAWallAddQuestionViewController ()<QuestTagCategoryViewControllerDelegate,UIGestureRecognizerDelegate>
{
    BOOL _isFirstLoad;
    SelectSubTag *_selectTag;
}
@property (retain, nonatomic) IBOutlet UIScrollView *containerScrollView;
@property (retain, nonatomic) IBOutlet UITextField *tagTextField;
@property (retain, nonatomic) IBOutlet UITextField *titleTextField;
@property (retain, nonatomic) IBOutlet UITextView *contentTextView;
@property (retain, nonatomic) IBOutlet UIButton *publicNickNameBtn;
@property (retain, nonatomic) IBOutlet UIButton *anonymousBtn;
@property (retain, nonatomic) IBOutlet UIButton *backBtn;
@property (retain, nonatomic) IBOutlet UILabel *placeHolderLabel;

@end

@implementation QAWallAddQuestionViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [_containerScrollView release];
    [_tagTextField release];
    [_titleTextField release];
    [_contentTextView release];
    [_publicNickNameBtn release];
    [_anonymousBtn release];
    [_backBtn release];
    [_selectTag release];
    [_placeHolderLabel release];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
    [super dealloc];
}

- (void)viewDidUnload
{
    [self setContainerScrollView:nil];
    [self setTagTextField:nil];
    [self setTitleTextField:nil];
    [self setContentTextView:nil];
    [self setPublicNickNameBtn:nil];
    [self setAnonymousBtn:nil];
    [self setBackBtn:nil];
    [self setPlaceHolderLabel:nil];
    [super viewDidUnload];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    _containerScrollView.top = self.view.height;
    _backBtn.alpha = 0;
    _isFirstLoad = YES;
    
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hanldTapGesture:)];
    tapGestureRecognizer.delegate = self;
    [self.view addGestureRecognizer:tapGestureRecognizer];
    [tapGestureRecognizer release];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    _backBtn.alpha = 0;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    if (_isFirstLoad)
    {
        [UIView animateWithDuration:0.5 animations:^{
            _containerScrollView.top = 0;
        }];
        _isFirstLoad = NO;
    }
    
    [UIView animateWithDuration:0.4 animations:^{
        _backBtn.alpha = 1;
    }];

}

#pragma mark - IBAction
- (IBAction)tapOnBackBtn:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)tapOnTagBtn:(id)sender {
    
    QuestTagCategoryViewController *questTagCategoryViewController = [[QuestTagCategoryViewController alloc] init];
    questTagCategoryViewController.delegate = self;
    [self.navigationController pushViewController:questTagCategoryViewController animated:YES];
    [questTagCategoryViewController release];
}

- (IBAction)tapOnPublicNickNameBtn:(id)sender {
    _publicNickNameBtn.backgroundColor = RGBCOLOR(0, 130, 255);
    _anonymousBtn.backgroundColor = [UIColor whiteColor];
    
    _publicNickNameBtn.enabled = NO;
    _anonymousBtn.enabled = YES;
}
- (IBAction)tapOnAnonymousBtn:(id)sender {
    _publicNickNameBtn.backgroundColor = [UIColor whiteColor];
    _anonymousBtn.backgroundColor = RGBCOLOR(0, 130, 255);
    
    _publicNickNameBtn.enabled = YES;
    _anonymousBtn.enabled = NO;
}
- (IBAction)tapOnOKBtn:(id)sender
{
    if (!_selectTag|| [@"" isEqualToString:_tagTextField.text])
    {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please select a tag"];
        return;
    }
    if ([@"" isEqualToString:_titleTextField.text])
    {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please enter a title"];
        return;
    }
    
    if ([@"" isEqualToString:_contentTextView.text])
    {
        [[HTActivityIndicator currentIndicator] displayMessage:@"Please enter your question"];
        return;
    }
    
    [self addQuestionRequest];
}

- (void)addQuestionRequest
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    
    if ([UserManager sharedManager].currentUser.userId)
    {
        [params setObject:[UserManager sharedManager].currentUser.userId forKey:@"memberId"];
    }
    
    [params setObject:_titleTextField.text forKey:@"title"];
    [params setObject:_contentTextView.text forKey:@"content"];
    [params setObject:_selectTag.tagId forKey:@"tagId"];
    if (_publicNickNameBtn.enabled)
    {
        [params setObject:@"1" forKey:@"is_anonymous"];
    }
    else
    {
        [params setObject:@"0" forKey:@"is_anonymous"];
    }
    
    [[ServiceHelper sharedService] requestServerForMethod:HotWordRequestTypeAddQuestion WithParameters:params AndCallBackScope:self AndSuccessSel:@"addSuccess:" AndFailedSel:@"addFailed:"];
    [[HTActivityIndicator currentIndicator] displayActivity:@"Submitting..."];
}


- (void)addSuccess:(NSObject *)result
{
    [[HTActivityIndicator currentIndicator] displayCompleted:@"Add Succeed!"];
    for (UIViewController *viewController in self.navigationController.viewControllers)
    {
        if ([viewController isKindOfClass:[QAWallViewController class]])
        {
            QAWallViewController *wallViewController = (QAWallViewController *)viewController;
            wallViewController.isNeedRefresh = YES;
        }
    }
   [self.navigationController popViewControllerAnimated:YES];
}

- (void)addFailed:(NSObject *)result
{
    [[HTActivityIndicator currentIndicator] displayFailed:@"Add Failed!"];
}

#pragma mark - UIGestureRecognizerDelegate

-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {    
    if ([touch.view isKindOfClass:[UIButton class]] || [touch.view isKindOfClass:[UITextField class]] || [touch.view isKindOfClass:[UITextView class]])
    {
        return NO;
    }
    return YES;
}

#pragma mark - UITextFieldDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [UIView animateWithDuration:0.3 animations:^{
        _containerScrollView.contentOffset = CGPointZero;
    }];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [_contentTextView becomeFirstResponder];

    return NO;
}

#pragma mark - UITextViewDelegate

- (void)textViewDidBeginEditing:(UITextView *)textView
{
    [UIView animateWithDuration:0.3 animations:^{
        [_containerScrollView setContentOffset:CGPointMake(0, _contentTextView.bottom - (self.view.height - MAX_KEYBOARD_HEIGHT)) animated:NO];
    }];
}

- (void)textViewDidChange:(UITextView *)textView
{
    if ([textView.text length] == 0)
    {
        _placeHolderLabel.hidden = NO;
    }
    else
    {
        _placeHolderLabel.hidden = YES;
    }
}


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([textView.text length] == 140)
    {
        if ([text length] < 1) //用于相应退格事件
        {
            textView.text = [textView.text substringToIndex:[textView.text length] - 1];
        }
        return NO;
    }
    
    if ([@"\n" isEqualToString:text])
    {
        [textView resignFirstResponder];
    }
    
    return YES;
}


-(void)keyboardWillShow:(NSNotification *)aNotification
{
    _containerScrollView.contentSize = CGSizeMake(_containerScrollView.width,_containerScrollView.bottom + MAX_KEYBOARD_HEIGHT);
}

- (void)keyboardWillHide:(NSNotification *)aNotification
{
    [UIView animateWithDuration:0.3 animations:^{
        _containerScrollView.contentSize = CGSizeMake(_containerScrollView.width, _containerScrollView.bottom);
    }];
}


- (void)hanldTapGesture:(UIGestureRecognizer *)recognizer
{
    [_titleTextField resignFirstResponder];
    [_contentTextView resignFirstResponder];

}

#pragma mark -  QuestTagCategoryViewControllerDelegate

- (void)questTagCategoryViewController:(QuestTagCategoryViewController *)viewController didSelectTag:(SelectSubTag *)tag;
{
    if (_selectTag)
    {
        RELEASE_SAFELY(_selectTag);
    }
    _selectTag = [tag retain];
    _tagTextField.text = _selectTag.selectTagTitle;
}



@end
